import React, { useState } from 'react';

import styles from './useCallback.css';

/**
 * useCallback 和 useMemo 没啥区别，
 * useMemo 把 arg[0] 执行了返回
 * useCallback 不执行
 */
function useCallback(cb: Function, deps: any[] = []) {
  const [state, setState] = useState(() => ({ cb, deps }));
  if (state.deps.length != deps.length) {
    console.log('use new callback deps length diff');
    setState({ cb, deps });
    return cb;
  }
  const oldDeps = state.deps;
  if (deps.find((dep, idx) => dep !== oldDeps[idx])) {
    console.log('use new callback deps item diff');
    setState({ cb, deps });
    return cb;
  }
  console.log('use cached callback');
  return state.cb;
}

export default function() {
  const [state, setState] = useState(0);
  const cb = useCallback((e: Event) => console.log(e.target, state), [state]);
  // const cb2 = (e: Event) => console.log(e.target, state);
  return (
    <div className={styles.normal}>
      <h1>Page useCallback</h1>
      <div onClick={cb}>state = {state}</div>
      <button onClick={() => setState(Math.ceil(Math.random() * 10))}>
        change state
      </button>
    </div>
  );
}
